﻿// *****************************************************************************
// **                   Ladenius MediaCenter TVSeries                         **
// ** ----------------------------------------------------------------------- **
// ** (c) 2008 by Jurjen Ladenius                                             **
// *****************************************************************************

#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ladenius.Series.Path;
using System.Collections.ObjectModel;
using Ladenius.Series.Path.Entities;
using Ladenius.Series.Business;
#endregion


namespace Ladenius.Series.Configuration.WinClient {
    /// <summary>
    /// Used for parsing series and episodes
    /// </summary>
    internal class Parser {

        #region Fields
        private TVDB _tvdb;
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the <see cref="Parser"/> class.
        /// </summary>
        internal Parser() {
            _tvdb = new TVDB();
        }
        #endregion

        #region Events
        public delegate void ProgressReportedEventHandler(object sender, string message);
        /// <summary>
        /// Occurs when parsing is completed.
        /// </summary>
        public event ProgressReportedEventHandler ProgressReported;
        /// <summary>
        /// Called when parsing is completed.
        /// </summary>
        protected virtual void OnProgressReported(string message) {
            ProgressReportedEventHandler handler = ProgressReported;
            if (handler != null)
                handler(this, message);
        }
        #endregion

        #region Methods - Parsing series and episodes
        /// <summary>
        /// Parses the series.
        /// </summary>
        /// <param name="parsedFiles">The parsed files.</param>
        internal void ParseSeries(ReadOnlyCollection<ParsedFile> parsedFiles, string languageAbbreviation) {

            if (parsedFiles.Count == 0) return;

            // Get Series from the list
            var newseries = from p in parsedFiles
                         group p by p.Series into g
                         select new { Series = g.Key, Episodes = g };

            List<Entities.Series> series = SeriesHome.GetAll();
            TheTVDB.Entities.Series tvdb_series;
            Entities.Series selected;

            foreach (var g in newseries) {

                // Find any existing series
               var existing = from s in series
                              where s.Name.Trim().ToLower() == g.Series.Trim().ToLower()
                              select s;

               selected = existing.SingleOrDefault<Entities.Series>();
               // Determine series
               if (selected == null) {
                   // new series, get TVDB info, create and save
                   tvdb_series = _tvdb.GetTVDBSeries(g.Series, languageAbbreviation);
                   selected = new Entities.Series() { 
                       SeriesID = int.MinValue,
                       Name = g.Series,
                       TVDB_SeriesID = tvdb_series == null ? int.MinValue : tvdb_series.ID };
               } else {
                   // update any TVDB information
                   tvdb_series = _tvdb.GetTVDBSeries(selected.TVDB_SeriesID, selected.Name, languageAbbreviation);
                   selected.TVDB_SeriesID = tvdb_series == null ? int.MinValue : tvdb_series.ID;
               }

                // Save the series
                selected = SeriesHome.Save (selected);
                
                // TODO: Cache the TheTVDB data to the database
                if (tvdb_series != null) {
                    OnProgressReported(string.Format("Linked series '{0}' to TheTVDB series '{1}'", selected.Name, tvdb_series.Name));
                } else {
                    OnProgressReported(string.Format("Could not link series '{0}' to any TheTVDB series", selected.Name));
                }

                // parse the seasons and episodes
                ParseSeasons(selected, g.Episodes.ToList<ParsedFile>());
            }
        }

        /// <summary>
        /// Parses the seasons.
        /// </summary>
        /// <param name="seriesID">The series ID.</param>
        /// <param name="Episodes">The episodes.</param>
        private void ParseSeasons(Entities.Series series, List<ParsedFile> Episodes) {
            //throw new NotImplementedException();
        }
        #endregion

    }
}
